package com.syj.qdp.framework.skywalking.core.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import io.opentracing.Span;
import io.opentracing.tag.Tags;
import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * @author Lyon
 */
public class TracerFrameworkUtils {


    public static void error(Span span, Throwable throwable){
        try {
            Tags.ERROR.set(span,true);
            if (throwable != null) {
                span.log(bulidErrorLog(throwable));
            }
        } catch (Exception ignore) {}
    }

    /**
     * 格式参考: https://ld246.com/article/1607866513663
     * @param throwable
     * @return
     */
    private static HashMap<String, Object> bulidErrorLog(Throwable throwable) {

        HashMap<String, Object> data = new HashMap<>();
        data.put("event",Tags.ERROR.getKey());
        data.put("log.kind",throwable.getClass().getName());
        data.put("log.object",throwable);
        String message = ExceptionUtil.getRootCauseMessage(throwable);
        data.put("message",message);
        StringWriter sw = new StringWriter();
        throwable.printStackTrace(new PrintWriter(sw));
        data.put("log.stack",sw.toString());
        return data;
    }

}
